<template>
  <div class="create-dealer-container">
      <el-steps
        :active="activeStep"
        finish-status="success"
        class="create-dealer-steps"
        align-center
      >
        <el-step title="Identity" />
        <el-step title="Business Info" />
        <el-step title="Settlement Info" />
      </el-steps>

      <el-form
        ref="createDealerFormRef"
        :model="createDealerForm"
        :rules="formRules"
        label-position="top"
        label-width="auto"
        class="create-dealer-form"
      >
        <!-- Step 1: Identity -->
        <div v-if="activeStep === 0">
          <el-form-item label="Mobile No" prop="mobileNo" required>
            <div class="mobile-input-wrapper">
              <el-select
                v-model="createDealerForm.countryCode"
                placeholder="+234"
                class="country-code-select"
                disabled
              >
                <el-option label="+234" value="+234" />
              </el-select>
              <el-input
                v-model="createDealerForm.mobileNo"
                placeholder="Please enter mobile number"
                type="number"
              />
            </div>
          </el-form-item>

          <el-form-item label="Choose Verification Type" prop="verificationType" required>
            <el-select
              v-model="createDealerForm.verificationType"
              placeholder="Please select Choose verification type"
            >
              <el-option label="NIN" value="nin" />
              <el-option label="BVN" value="bvn" />
            </el-select>
          </el-form-item>

          <el-form-item label="NIN/BVN" prop="ninBvn" required>
            <el-input
              v-model="createDealerForm.ninBvn"
              placeholder="Please enter NIN/BVN"
              type="number"
            />
          </el-form-item>

          <el-form-item label="Dealer Name" required>
            <div style="display: flex; gap: 10px">
              <el-input
                v-model="createDealerForm.firstName"
                placeholder="First Name"
                style="flex: 1"
              />
              <el-input
                v-model="createDealerForm.middleName"
                placeholder="Middle Name (Option)"
                style="flex: 1"
              />
              <el-input
                v-model="createDealerForm.lastName"
                placeholder="Last Name"
                style="flex: 1"
              />
            </div>
          </el-form-item>

          <el-form-item label="Date of Birth" prop="dateOfBirth" required>
            <el-date-picker
              v-model="createDealerForm.dateOfBirth"
              type="date"
              placeholder="Select date"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="Gender" prop="gender" required>
            <el-radio-group v-model="createDealerForm.gender">
              <el-radio label="male">Male</el-radio>
              <el-radio label="female">Female</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="Residential Address" required>
            <el-select
              v-model="createDealerForm.state"
              placeholder="State/City/LGA"
              style="width: 100%; margin-bottom: 10px"
            >
              <el-option label="State" value="State" />
              <el-option label="City" value="City" />
              <el-option label="LGA" value="LGA" />
            </el-select>
          </el-form-item>
          <el-form-item label="Street Name And House No">
            <el-input
              v-model="createDealerForm.streetName"
              placeholder="Please input street name and house no"
            />
          </el-form-item>

          <el-form-item label="Email Address" prop="emailAddress" required>
            <el-input
              v-model="createDealerForm.emailAddress"
              placeholder="Please enter email address"
              type="email"
            />
          </el-form-item>

          <el-form-item label="Whatsapp" prop="whatsapp" required>
            <el-input
              v-model="createDealerForm.whatsapp"
              placeholder="Please enter your whatsapp number"
            />
            <el-checkbox
              v-model="createDealerForm.sameAsPhoneNumber"
              @change="handleSameAsPhoneNumberChange"
              >Same as Phone Number</el-checkbox
            >
          </el-form-item>

          <el-form-item label="Alternate Phone Number" prop="alternatePhoneNumber">
            <div class="mobile-input-wrapper">
              <el-select
                v-model="createDealerForm.alternateCountryCode"
                placeholder="+234"
                class="country-code-select"
                disabled
              >
                <el-option label="+234" value="+234" />
              </el-select>
              <el-input
                v-model="createDealerForm.alternatePhoneNumber"
                placeholder="Please enter your alternate phone number"
                type="number"
              />
            </div>
          </el-form-item>

          <el-form-item label="BD Group Photo" prop="bdGroupPhoto" required>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              v-model:file-list="createDealerForm.bdGroupPhoto"
              :on-change="(file, fileList) => handleChange(file, fileList, 'bdGroupPhoto')"
            >
              <div class="el-upload__text">Drag file here or <em>click to upload</em></div>
              <template #tip>
                <div class="el-upload__tip">Please upload a group photo of BD&Dealer</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="StoreFront Photo" prop="storeFrontPhoto" required>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              v-model:file-list="createDealerForm.storeFrontPhoto"
              :on-change="(file, fileList) => handleChange(file, fileList, 'storeFrontPhoto')"
            >
              <div class="el-upload__text">Drag file here or <em>click to upload</em></div>
              <template #tip>
                <div class="el-upload__tip">Please upload a Photo of StoreFront with Dealer</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="Interior Photo" prop="interiorPhoto" required>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              v-model:file-list="createDealerForm.interiorPhoto"
              :on-change="(file, fileList) => handleChange(file, fileList, 'interiorPhoto')"
            >
              <div class="el-upload__text">Drag file here or <em>click to upload</em></div>
              <template #tip>
                <div class="el-upload__tip">Please upload a Photo of Interior with Dealer</div>
              </template>
            </el-upload>
          </el-form-item>
        </div>

        <!-- Step 2: Business Info -->
        <div v-if="activeStep === 1">
          <el-form-item label="BD ID" prop="bdId" required>
            <el-input v-model="createDealerForm.bdId" placeholder="Please input bd id" />
          </el-form-item>

          <el-form-item label="Business License" prop="businessLicense">
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              v-model:file-list="createDealerForm.businessLicense"
              :on-change="(file, fileList) => handleChange(file, fileList, 'businessLicense')"
            >
              <div class="el-upload__text">Drag file here or <em>click to upload</em></div>
              <template #tip>
                <div class="el-upload__tip">Please upload Business License</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="Business Registration Number" prop="businessRegistrationNumber">
            <el-input
              v-model="createDealerForm.businessRegistrationNumber"
              placeholder="Please enter business registration number"
            />
          </el-form-item>

          <el-form-item label="Business Registration Date" prop="businessRegistrationDate">
            <el-date-picker
              v-model="createDealerForm.businessRegistrationDate"
              type="date"
              placeholder="Please select business registration date"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="Emergency Contact Name" prop="emergencyContactName" required>
            <el-input
              v-model="createDealerForm.emergencyContactName"
              placeholder="Please select your emergency contact name"
            />
          </el-form-item>

          <el-form-item label="Emergency Contact Relation" prop="emergencyContactRelation" required>
            <el-select
              v-model="createDealerForm.emergencyContactRelation"
              placeholder="Please select your emergency contact relation"
              filterable
            >
              <el-option label="Spouse" value="spouse" />
              <el-option label="Parent" value="parent" />
              <el-option label="Child" value="child" />
              <el-option label="Sibling" value="sibling" />
              <el-option label="Friend" value="friend" />
              <el-option label="Other" value="other" />
            </el-select>
          </el-form-item>

          <el-form-item label="Emergency Contact Number" prop="emergencyContactNumber" required>
            <div class="mobile-input-wrapper">
              <el-select
                v-model="createDealerForm.emergencyCountryCode"
                placeholder="+234"
                class="country-code-select"
                disabled
              >
                <el-option label="+234" value="+234" />
              </el-select>
              <el-input
                v-model="createDealerForm.emergencyContactNumber"
                placeholder="Please enter your emergency contact number"
                type="number"
              />
            </div>
          </el-form-item>

          <el-form-item label="Monthly sales (units)" prop="monthlySales">
            <el-input
              v-model="createDealerForm.monthlySales"
              placeholder="Please enter monthly sales"
              type="number"
            />
          </el-form-item>
        </div>

        <!-- Step 3: Settlement Info -->
        <div v-if="activeStep === 2">
          <el-form-item label="Bank Name" prop="bankName" required>
            <el-select v-model="createDealerForm.bankName" placeholder="Please select bank name">
              <el-option label="Access Bank" value="access" />
              <el-option label="Guaranty Trust Bank" value="gtb" />
              <el-option label="Zenith Bank" value="zenith" />
              <el-option label="First Bank" value="first" />
            </el-select>
          </el-form-item>

          <el-form-item label="Account Number" prop="accountNumber" required>
            <el-input
              v-model="createDealerForm.accountNumber"
              placeholder="Please enter account number"
              type="number"
            />
          </el-form-item>

          <el-form-item label="Account Name" prop="accountName" required>
            <el-input
              v-model="createDealerForm.accountName"
              placeholder="Please enter account name"
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="form-actions">
        <el-button @click="handlePrevious" v-if="activeStep > 0">Previous</el-button>
        <el-button type="primary" @click="handleNext" v-if="activeStep < 2">Next</el-button>
        <el-button type="primary" @click="handleSubmit" v-if="activeStep === 2">Submit</el-button>
      </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import {
  ElOption,
  ElInput,
  ElMessage,
  ElSteps,
  ElStep,
  ElSelect,
  ElForm,
  ElFormItem,
  ElButton,
  ElRadioGroup,
  ElRadio,
  ElDatePicker,
  ElCheckbox,
  ElUpload
} from 'element-plus'

// 表单引用
const createDealerFormRef = ref()

// 步骤状态
const activeStep = ref<number>(0)

// 表单数据
const createDealerForm = reactive({
  // Step 1: Identity
  countryCode: '+234',
  mobileNo: '',
  verificationType: '',
  ninBvn: '',
  firstName: 'XIAOHUI',
  middleName: '',
  lastName: 'WANG',
  dateOfBirth: '1994-04-17',
  gender: 'male',
  state: '',
  streetName: '',
  emailAddress: '',
  whatsapp: '',
  sameAsPhoneNumber: false,
  alternateCountryCode: '+234',
  alternatePhoneNumber: '',
  bdGroupPhoto: [],
  storeFrontPhoto: [],
  interiorPhoto: [],
  // Step 2: Business Info
  businessName: '',
  businessType: '',
  address: '',
  bdId: '',
  financialModel: '',
  tinNumber: '',
  businessLicense: [],
  businessRegistrationNumber: '',
  businessRegistrationDate: '',
  emergencyContactName: '',
  emergencyContactRelation: '',
  emergencyCountryCode: '+234',
  emergencyContactNumber: '',
  fixedAssets: '',
  yearsInBusiness: '',
  monthlySales: '',

  // Step 3: Settlement Info
  bankName: '',
  accountNumber: '',
  accountName: ''
})

// 表单验证规则
const formRules = reactive({
  mobileNo: [
    { required: true, message: 'Please enter mobile number', trigger: 'blur' },
    { min: 10, max: 10, message: 'Mobile number must be 10 digits', trigger: 'blur' }
  ],
  verificationType: [
    { required: true, message: 'Please select verification type', trigger: 'change' }
  ],
  ninBvn: [
    { required: true, message: 'Please enter NIN/BVN', trigger: 'blur' },
    { min: 11, max: 11, message: 'NIN/BVN must be 11 digits', trigger: 'blur' }
  ],
  firstName: [{ required: true, message: 'Please enter first name', trigger: 'blur' }],
  lastName: [{ required: true, message: 'Please enter last name', trigger: 'blur' }],
  dateOfBirth: [{ required: true, message: 'Please select date of birth', trigger: 'change' }],
  gender: [{ required: true, message: 'Please select gender', trigger: 'change' }],
  state: [{ required: true, message: 'Please select state/city/lga', trigger: 'change' }],
  emailAddress: [
    { required: true, message: 'Please enter email address', trigger: 'blur' },
    { type: 'email', message: 'Please enter valid email address', trigger: 'blur' }
  ],
  whatsapp: [{ required: true, message: 'Please enter whatsapp number', trigger: 'blur' }],
  bdGroupPhoto: [{ required: true, message: 'Please upload BD group photo', trigger: 'change' }],
  storeFrontPhoto: [
    { required: true, message: 'Please upload store front photo', trigger: 'change' }
  ],
  interiorPhoto: [{ required: true, message: 'Please upload interior photo', trigger: 'change' }],
  businessName: [{ required: true, message: 'Please enter business name', trigger: 'blur' }],
  businessType: [{ required: true, message: 'Please select business type', trigger: 'change' }],
  address: [{ required: true, message: 'Please enter address', trigger: 'blur' }],
  bdId: [{ required: true, message: 'Please input bd id', trigger: 'blur' }],
  financialModel: [{ required: true, message: 'Please select financial model', trigger: 'change' }],
  emergencyContactName: [
    { required: true, message: 'Please enter emergency contact name', trigger: 'blur' }
  ],
  emergencyContactRelation: [
    { required: true, message: 'Please select emergency contact relation', trigger: 'change' }
  ],
  emergencyContactNumber: [
    { required: true, message: 'Please enter emergency contact number', trigger: 'blur' }
  ],
  bankName: [{ required: true, message: 'Please select bank name', trigger: 'change' }],
  accountNumber: [
    { required: true, message: 'Please enter account number', trigger: 'blur' },
    { min: 10, max: 10, message: 'Account number must be 10 digits', trigger: 'blur' }
  ],
  accountName: [{ required: true, message: 'Please enter account name', trigger: 'blur' }]
})

// 处理上一步
const handlePrevious = () => {
  activeStep.value--
}
const handleChange = (file: any, fileList: any, propName: string) => {
  // 确保只保留最后一个文件
  const newFileList = fileList.slice(-1)
  // 正确更新响应式数据
  createDealerForm[propName] = newFileList
  console.log(`${propName}:`, newFileList)
}

// 处理Same as Phone Number复选框变化
const handleSameAsPhoneNumberChange = (checked: boolean) => {
  if (checked && createDealerForm.mobileNo) {
    createDealerForm.whatsapp = createDealerForm.mobileNo
  }
}

// 处理下一步
const handleNext = async () => {
  if (!createDealerFormRef.value) return

  // 验证当前步骤的表单字段，只验证当前步骤可见的字段
  let isValid = true

  // 根据当前步骤确定需要验证的字段
  const fieldsToValidate = []
  if (activeStep.value === 0) {
    // Step 1 fields
    fieldsToValidate.push(
      'mobileNo',
      'verificationType',
      'ninBvn',
      'firstName',
      'lastName',
      'dateOfBirth',
      'gender',
      'state',
      'emailAddress',
      'whatsapp',
      'bdGroupPhoto',
      'storeFrontPhoto',
      'interiorPhoto'
    )
  } else if (activeStep.value === 1) {
    // Step 2 fields
    fieldsToValidate.push(
      'bdId',
      'emergencyContactName',
      'emergencyContactRelation',
      'emergencyContactNumber'
    )
  }

  // 逐个验证字段
  for (const field of fieldsToValidate) {
    try {
      await createDealerFormRef.value.validateField(field)
    } catch (error) {
      isValid = false
      break
    }
  }

  if (isValid) {
    activeStep.value++
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!createDealerFormRef.value) return

  // 分步骤验证，确保每个步骤的必填字段都已填写
  let isValid = true

  // 验证所有步骤中标记为必填的字段
  const allRequiredFields = [
    // Step 1 fields
    'mobileNo',
    'verificationType',
    'ninBvn',
    'firstName',
    'lastName',
    'dateOfBirth',
    'gender',
    'state',
    'emailAddress',
    'whatsapp',
    'bdGroupPhoto',
    'storeFrontPhoto',
    'interiorPhoto',
    // Step 2 fields
    'bdId',
    'emergencyContactName',
    'emergencyContactRelation',
    'emergencyContactNumber',
    // Step 3 fields - 最后一步的字段
    'bankName',
    'accountNumber',
    'accountName'
  ]
  // 逐个验证所有必填字段
  for (const field of allRequiredFields) {
    try {
      await createDealerFormRef.value.validateField(field)
    } catch (error) {
      isValid = false
      break
    }
  }

  if (isValid) {
    // 模拟提交数据
    console.log('Dealer data submitted:', createDealerForm)

    // 显示成功消息
    ElMessage.success('Dealer created successfully!')

    // 重置表单
    // createDealerFormRef.value.resetFields()
    activeStep.value = 0
  }
}
</script>

<style scoped>
.create-dealer-steps {
  margin-bottom: 40px;
}

/* 减小el-step组件的字体大小 */
.el-step__title {
  font-size: 14px !important;
}

.create-dealer-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.mobile-input-wrapper {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 100%;
}

.country-code-select {
  flex: 0.3;
}

.mobile-input-wrapper .el-input {
  flex: 0.7;
}

.form-actions {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 24px;
}

.financial-model-desc {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
  line-height: 1.5;
}

.financial-model-desc p {
  margin: 5px 0;
}
</style>
